import Vue from 'vue';
import { ref, onMounted, getCurrentInstance, computed } from '@vue/composition-api'
import staticConst from "@/js/const/StaticConst.js";
import https from "@/js/https/Https.js";
import config from "@/js/conf/Config.js";
import { formatTimeString, getCurrentDateFormatted } from '@/utils/common.js'

// 创建一个单例状态
const state = {
    isToDoModal: ref(false), // 是否是待办模块
    tabType: ref(''), // 单据类型1出库单；2入库单；3调拨单；4盘点单；5报损单
    query: ref({
        type: 1, // 单据类型1出库单；2入库单；3调拨单；4盘点单；5报损单
        st: '3', // 状态 1待确认(未启用) 2已确认 3待出入库 4已出入库 21草稿单 22已作废
        kw: '', // 关键词，可单独传值
        storeid: '', // 仓库id
        shipp_type: '', // 配送方式
        time: 0, // 时间类型，1今日2本月3本季4本年5自定义
        stime: '', // 起始时间2020-03-03
        pfrom: 0, // 分页起点
        pnum: 20, // 分页数量
    }),

    // 页面数据
    box_index_key: ref("3"),
    box_list_arr: ref([]),
    templates: ref([]),
    listData: ref([]),

    time_data: ref([{
        id: 0,
        name: "全部日期",
    },
    {
        id: "1",
        name: "今日",
    },
    {
        id: "2",
        name: "本月",
    },
    {
        id: "3",
        name: "本季",
    },
    {
        id: "4",
        name: "本年",
    },
    ]),

    // 状态变量
    shopid_yd: ref(0),
    pfrom: ref(0),
    lLoading: ref(false),
    lNoMore: ref(false),
    isEdit: ref(false),
    isCartAddFrom: ref(false),
    detailID: ref(null),
    selectedIndex: ref(0),
    recordSelectedIndex: ref(0),

    // 组件引用
    marketingAddRef: ref(null),
    leftListRef: ref(null),
    detaillRef: ref(null),

    stores_list: ref([]), // 仓库列表
    sfee_list: ref([]), // 配送方式
    detailData: ref({}), // 详情数据

    cart_info: ref({}),
    gd_ls: ref([]),
    // 初始化表单数据
    objectForm: ref({
        atime_txt: '', // 默认当前本地日期时间
        customerid: "",
        isdo: "1",
        isprint: "2",
        shipp_info: {},
        storeid: '0',
        storeid2: undefined, // 调入库仓库
        storeid_print: "",
        uid_cp: "", // 仓库人员
        txt_imgs: [],
        txt: '',
        suppid: '',
        shipp_type: '', // 配送方式
    }),
    // 新增仓库列表数据（假设）
    warehouseList: ref([]),
    warehouse2List: ref([]), // 调入仓库列表
    deStoreList: ref([]),
    ucp_ls_data: ref([]),
    ck_orders_setting: ref({}), // 开单-相关设置读取
}

const titleName = computed(() => {
    return state.tabType.value == 'into_warehouse' ? '入库' :
        state.tabType.value == 'transfer_warehouse' ? '调拨' :
            state.tabType.value == 'out_warehouse' ? '出库' : ''
})

export const useOrderReceiptState = () => {
    const maxPnum = 20
    // 获取当前组件实例和全局状态
    const { proxy } = getCurrentInstance()

    // 状态切换
    const handleClick = () => {
        state.isEdit.value = false
        state.isCartAddFrom.value = false
        state.selectedIndex.value = 0
        state.query.value.st = state.box_index_key.value
        getEventLs(true)
    }

    // 选择分店
    const selectFun = (e) => {
        getEventLs(true)
    }

    const loadFun = () => {
        if (state.lNoMore.value) return
        state.pfrom.value += 20
        getEventLs(false)
    }

    const clickItem = (index) => {
        state.detailData.value = {}
        state.isEdit.value = false
        state.isCartAddFrom.value = false
        state.selectedIndex.value = index
        state.recordSelectedIndex.value = index
        state.detailID.value = state.listData.value[index]?.id
        getEventInfo()
    }

    // 列表数据
    const getEventLs = async (t = true) => {
        state.lLoading.value = true
        if (t == true) {
            state.selectedIndex.value = 0
            state.pfrom.value = 0
            state.listData.value = []
        }
        let param = {
            ...state.query.value,
            shopid_yd: state.shopid_yd.value,
            st: state.box_index_key.value,
            pnum: maxPnum,
            pfrom: state.pfrom.value,
            stime: "",
            dtime: "",
        }
        try {
            let res = await proxy.$api({ url: config.ck_order_order_ls, data: param })
            state.lLoading.value = false
            if (res.status == 1) {
                let result = res?.data
                if (result) {
                    state.listData.value.push(...result)
                    // 确保索引在有效范围内
                    const validIndex = Math.min(state.selectedIndex.value, state.listData.value.length - 1)
                    state.detailID.value = state.listData.value[validIndex]?.id
                    getEventInfo()
                    if (res.status == 1 && result.length < maxPnum) {
                        state.lNoMore.value = true
                    } else {
                        state.lNoMore.value = false
                    }
                } else {
                    state.lNoMore.value = true;
                }
            } else {
                state.lNoMore.value = true
            }
        } catch (error) {
            state.lLoading.value = false
            state.lNoMore.value = true
        } finally {
            state.lLoading.value = false
        }
    }

    // 获取详情
    const getEventInfo = async () => {
        let param = {
            odid: state.detailID.value,
            st: state.query.value.st,
        }
        try {
            let res = await proxy.$api({ url: config.ck_order_order_info, data: param })
            let result = res.data
            if (res.status == 1 && result) {
                result.goods_ls = result.goods_ls.map(item => {
                    return {
                        ...item,
                        img: item.gdimg,
                        spec_title: combinaFc(item),
                    }
                })
                state.detailData.value = {
                    ...result,
                }
            }
        } catch (error) { }
    }

    // 开单购物车-读取
    const getCartInfoFun = async () => {
        try {
            let res = await proxy.$api({ url: config.ck_order_cart_info, data: {} })
            if (!res.data) return;
            let result = res.data
            state.cart_info.value = result
            state.gd_ls.value = result?.gd_ls
            if (result?.gd_ls && result?.gd_ls.length > 0) {
                getOrderCheckout()
            }
        } catch (error) {
            console.error('开单购物车-读取失败:', error)
        }
    }

    // 开单购物车-加购/修改价格数量 
    const getOrderCheckout = async () => {
        try {
            let res = await proxy.$api({ url: config.ck_order_order_checkout, data: { type: 1 } })
            if (res.status == 1) {
                let result = res?.data
                state.objectForm.value = {
                    ...state.objectForm.value,
                    ...result,
                    shipp_info: result?.address_info || {},
                    storeid: result?.store_ls[0]?.id || '',
                    storeid2: undefined,
                    uid_cp: result?.user_ls[0]?.uid ? String(result.user_ls[0].uid) : '',
                    atime_txt: result?.time || getCurrentDateFormatted(),
                }
                state.warehouseList.value = [{ id: '0', name: `暂时不${titleName.value}` }, ...result?.store_ls]
                state.warehouse2List.value = [...result?.store_ls]
            }
        } catch (error) {
            console.error('开单购物车-加购/修改价格数量失败:', error)
        }
    }

    // 获取经手人
    const getUcpls = async () => {
        let res = await proxy.$api({ url: config.UCP_LS, data: { md: staticConst.ORDER_CK } });
        if (res.status == 1 && res.data) {
            state.ucp_ls_data.value = res.data.map(vm => {
                return {
                    id: vm.uid,
                    name: vm.name,
                    label: vm.name
                }
            })
        }
    }

        // 获取经手人
    const getCkOrderSettingSell = async () => {
        let res = await proxy.$api({ url: config.ck_order_setting_sell, data: {} });
        if (res.status == 1) {
            state.ck_orders_setting.value = res.data
            console.log('state.ck_orders_setting.value开单-相关设置读取:', state.ck_orders_setting.value)
        }
    }

    /** 详情页面 获取仓库列表***/
    const getStoreList = async () => {
        let param = {};
        param.ismy = 1;
        param.md = staticConst.ORDER_CK;
        let res = await proxy.$api({ url: config.STORE_LS, data: param });
        if (!res) return;
        if (res.status == 1) {
            if (!res.data) return;
            state.deStoreList.value = res.data;
        }
    }

    // 合并规格
    const combinaFc = (item) => {
        let spec_title = ''
        if (item.brand_txt) {
            spec_title = item.brand_txt
        }
        if (item.brand_txt && item.cattitle) {
            spec_title = item.brand_txt + '|' + item.cattitle
        }
        return spec_title + '|' + item.item_no
    }

    const refreshFun = () => {
        state.lNoMore.value = false
        state.lLoading.value = false
        state.pfrom.value = 0
        state.detailID.value = ''
        state.listData.value = []
    }

    // 处理编辑和停止事件
    const editStopTpBmFun = (data) => {

    }

    // 处理停止事件
    const stopTpBmFun = (data) => {
        // 刷新列表
        getEventLs(true)
    }

    // 提交表单
    const ckOrderOrderAdd = async (params) => {
        let res = await proxy.$api({ url: config.ck_order_order_add, data: params })
        if (res.status == 1) {
            proxy.$message({
                message: '提交成功',
                type: 'success',
            })
            setTimeout(() => {
                if (state.isToDoModal.value) {
                    getEventLs(true)
                } else {
                    if (state.isCartAddFrom.value) {
                        state.isEdit.value = false
                        state.isCartAddFrom.value = false
                        state.selectedIndex.value = 0
                        if (params?.storeid && params?.storeid2 && params?.isdo != 1 && state.tabType.value == 'transfer_warehouse') {
                            state.query.value.st = '3'
                            state.box_index_key.value = '3'
                        } else if (params?.storeid != '0' && params?.backup != 1) {
                            state.query.value.st = '4'
                            state.box_index_key.value = '4'
                        } else if (params?.backup == 1) {
                            state.query.value.st = '21'
                            state.box_index_key.value = '21'
                        } else {
                            state.query.value.st = '3'
                            state.box_index_key.value = '3'
                        }
                        getEventLs(true)
                    } else {
                        getEventInfo()
                    }
                }
            }, 800);
        } else {
            proxy.$message({
                message: res?.msg || '操作失败',
                type: 'error',
            })
        }
    }

    /***  初始化仓库数据  SHOP_LS ***/
    const createdStoreList = async () => {
        state.stores_list.value = []
        try {
            let res = await proxy.$api({ url: config.STORE_LS, data: { md: staticConst.ORDER_CK, ismy: '' } });
            if (!res) return;
            if (!res.data) return;
            state.stores_list.value.push({ id: '', name: '全部仓库' }, ...res.data);
        } catch (error) {
            console.error('配送方式-列表失败:', error)
        }
    }

    // 配送方式-列表
    const getSfeeLsFun = async () => {
        state.sfee_list.value = []
        try {
            let res = await proxy.$api({ url: config.compset_sfee_ls, data: {} })
            if (!res.data) return;
            state.sfee_list.value.push({ id: '', title: '全部配送方式' }, ...res.data)
        } catch (error) {
            console.error('配送方式-列表失败:', error)
        }
    }

    // 初始化
    const initialize = () => {
        createdStoreList()
        getEventLs()
    }

    // 归零初始化
    const resetFun = () => {
        state.tabType = ref('')
        state.box_index_key = ref("3")
        state.query = ref({
            type: 1,
            st: '3',
            kw: '',
            storeid: '',
            storeid2: undefined,
            shipp_type: '',
            time: 0,
            stime: '',
            pfrom: 0,
            pnum: 20,
        })
    }

    const addOrEdt = () => {
        getCartInfoFun()
        getUcpls()
        getCkOrderSettingSell()
        if (state.tabType.value == 'transfer_warehouse') {
            getSfeeLsFun()
        }
        state.selectedIndex.value = null
        state.isCartAddFrom.value = !state.isCartAddFrom.value
    }

    return {
        ...state,
        getEventLs,
        loadFun,
        selectFun,
        clickItem,
        handleClick,
        refreshFun,
        editStopTpBmFun,
        stopTpBmFun,
        initialize,
        resetFun,
        getEventInfo,
        addOrEdt,
        ckOrderOrderAdd,
        getSfeeLsFun,
        getCartInfoFun,
        getStoreList
    }
}